// 获取Cookie函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 检查登录状态并更新导航栏
async function updateAuthNav() {
    const authNav = document.getElementById('auth-nav');
    const sessionToken = getCookie('session_token');
    const userId = getCookie('username');

    if (!sessionToken || !userId) {
        // 未登录状态
        authNav.innerHTML = `
                    <li class="nav-item">
                        <a class="nav-link" href="/login/">登录</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/register/">注册</a>
                    </li>
                `;
        return;
    }

    try {
        // 检查会话是否有效
        const response = await fetch('/api/islogin/');
        const data = await response.json();

        if (data.ok) {
            // 已登录状态，获取用户信息
            const userResponse = await fetch(`/api/getuserinfo/?id=${userId}`);
            const userData = await userResponse.json();

            authNav.innerHTML = `
                        <li class="nav-item">
                            <a class="nav-link" href="/upload/">上传图片</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/user/${userId}/">我的主页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/logout/">退出</a>
                        </li>
                    `;
        } else {
            // 会话无效
            authNav.innerHTML = `
                        <li class="nav-item">
                            <a class="nav-link" href="/login/">登录</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/register/">注册</a>
                        </li>
                    `;
        }
    } catch (error) {
        console.error('检查登录状态失败:', error);
        authNav.innerHTML = `
                    <li class="nav-item">
                        <a class="nav-link" href="/login/">登录</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/register/">注册</a>
                    </li>
                `;
    }
}

// 页面加载时更新导航栏
document.addEventListener('DOMContentLoaded', function () {
    updateAuthNav();
});